package com.kexin.controller;

import com.kexin.common.result.Result;
import com.kexin.common.result.ResultCode;
import com.kexin.common.utils.RandomUtils;
import com.kexin.pojo.*;
import com.kexin.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/voucher")
public class VoucherController {
    @Autowired
    private TVoucherService tVoucherService;
    @Autowired
    private VUserInfoService vUserInfoService;
    @Autowired
    private TItemService tItemService;
    @Autowired
    private TItmedetailVService tItmedetailVService;
    @Autowired
    private TVoucherEntryService tVoucherEntryService;


    //销售凭证导入
    @ApiOperation(value = "sellVoucher",notes = "销售凭证生成")
    @PostMapping("/sellVoucher")
    public Result<String> sellVoucher(@RequestBody List<Map<String, String>> parameters) {
        if (parameters.size()<1){
            return Result.newError("数组不能为空");
        }
        Result<String> result = Result.newSuccess();
        //查询凭证主表
        Integer voucherNumMax = tVoucherService.getVoucherNumMax();
        Integer fSerialNumMax = tVoucherService.getFSerialNumMax(); //获取凭证表序号最大值
        // 插入凭证主表
        TVoucher tVoucher = new TVoucher();
        tVoucher.setFdate(new Date());
        tVoucher.setFtransdate(new Date());
        tVoucher.setFyear(Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()))); //会计年度
        tVoucher.setFperiod(Integer.valueOf(new SimpleDateFormat("MM").format(new Date()))); //会计期间
        tVoucher.setFgroupid(1); //凭证字内码
        tVoucher.setFnumber(voucherNumMax + 1); //凭证号
        tVoucher.setFreference(null); //参考信息
        tVoucher.setFexplanation("系统生成"); //备注
        tVoucher.setFattachments(0); //附件张数
        tVoucher.setFentrycount(parameters.size()); //分录数 动态获取
        tVoucher.setFdebittotal(new BigDecimal(0)); //借方金额合计初始化
        tVoucher.setFcredittotal(new BigDecimal(0)); //贷方金额合计初始化
        tVoucher.setFinternalind(null); // 机制凭证
        tVoucher.setFchecked(false); //是否审核
        tVoucher.setFposted(false); //是否过账
        tVoucher.setFpreparerid(16394); // 制单人
        tVoucher.setFcheckerid(-1); //审核人
        tVoucher.setFposterid(-1); //记账人
        tVoucher.setFcashierid(-1); // 出纳人
        tVoucher.setFhandler(null); //会计主管
        tVoucher.setFobjectname(null); //对象接口
        tVoucher.setFparameter(null); //接口参数
        tVoucher.setFserialnum(fSerialNumMax+1); //凭证表序号
        tVoucher.setFtrantype(0);
        tVoucher.setFownergroupid(1);
        Integer Pid = tVoucherService.add(tVoucher); // 获取凭证表id

        //获取分录表参数
        int i = 0;
        BigDecimal initMoney = new BigDecimal(0);
        for (Map<String, String> parameter : parameters) {
            String anAbstract = parameter.get("abstract");//获取摘要
            if (anAbstract==null || anAbstract.length() <1){
                return Result.newError(ResultCode.AN_ABSTRACT_NULL);

            }
            String name =  parameter.get("name");//客户名称
            if (name==null || name.length() <1){
                return Result.newError(ResultCode.NAME_NULL);

            }
            String userId =  parameter.get("userId");// 客户id
            if (userId==null || userId.length() <1){
                return Result.newError(ResultCode.USER_ID_NULL);
            }
            String money = parameter.get("money");
            if (money==null || money.length() <1){
                return Result.newError(ResultCode.COMMON_MESSAGE);
            }
            //根据客户id查询金蝶对应客户
            List<VUserInfo> user = vUserInfoService.getUser(userId);
            if (user.size() < 1) {
                //添加客户
                VUserInfo vUserInfo = new VUserInfo();
                String generateString = RandomUtils.generateString(8); //客户自定义id
                vUserInfo.setItemId(generateString);
                vUserInfo.setUserId(userId);
                vUserInfoService.insertUser(vUserInfo);
                TItem tItem = new TItem();
                tItem.setFitemclassid(1);
                tItem.setFparentid(0);
                tItem.setFlevel((short) 1);
                tItem.setFshortnumber(generateString);
                tItem.setFfullnumber(generateString);
                tItem.setFdetail(true);
                tItem.setFdeleted((short) 0);
                tItem.setUuid(UUID.randomUUID().toString());
                tItem.setFname(name);
                tItem.setFnumber(generateString);
                tItemService.insertUser(tItem); //插入到金蝶客户表
                //获取客户表主键id
                List<TItem> tItems = tItemService.getItemId(generateString);
                if (tItems.size() > 0) {
                    Integer fitemid = tItems.get(0).getFitemid();
                    //获取t_ItemDetailV 表主键id
                    Integer itemDetaiId = 0;
                    List<TItemdetailv> info = tItmedetailVService.getInfo(fitemid);
                    if (info.size() > 0) {
                        itemDetaiId = info.get(0).getFdetailid();
                    } else {
                        //获取主键id 插入到 t_ItemDetailV 表
                        List<TItemdetailv> infoSort = tItmedetailVService.getInfoSort(1);
                        itemDetaiId = infoSort.get(0).getFdetailid() + 1; // 获取主键id 模拟自增
                        TItemdetailv tItemdetailvKey = new TItemdetailv();
                        tItemdetailvKey.setFitemid(fitemid);
                        tItemdetailvKey.setFitemclassid(1);
                        tItemdetailvKey.setFdetailid(itemDetaiId);
                        tItmedetailVService.insertInfo(tItemdetailvKey);
                    }
                    //分录表插入
                    TVoucherentry tVoucherentry = new TVoucherentry();
                    tVoucherentry.setFvoucherid(Pid); //凭证主表id
                    tVoucherentry.setFentryid(i); //分录号
                    tVoucherentry.setFexplanation(anAbstract); //摘要
                    tVoucherentry.setFaccountid(1031); //科目id 客户
                    tVoucherentry.setFcurrencyid(1); //币别
                    tVoucherentry.setFexchangerate(1d); // 汇率
                    tVoucherentry.setFdc((short) 1); // 余额的方向 0贷方 1借方
                    tVoucherentry.setFamountfor(new BigDecimal(money));// 原币金额
                    tVoucherentry.setFamount(new BigDecimal(money)); //本币金额
                    tVoucherentry.setFquantity(0d); //数量
                    tVoucherentry.setFmeasureunitid(0); //计量单位
                    tVoucherentry.setFunitprice(0d); //单价
                    tVoucherentry.setFinternalind(null); //机制凭证
                    tVoucherentry.setFaccountid2(1031); //对方科目
                    tVoucherentry.setFsettletypeid(0); //结算方式
                    tVoucherentry.setFsettleno(null);
                    tVoucherentry.setFcashflowitem(0);
                    tVoucherentry.setFtaskid(0); // 项目任务id
                    tVoucherentry.setFresourceid(0); // 项目资源id
                    tVoucherentry.setFtransno(null); // 业务号
                    tVoucherentry.setFdetailid(itemDetaiId);  // 项目核算使用id
                    tVoucherEntryService.insertInfo(tVoucherentry);
                    i++;
                    initMoney = initMoney.add(new BigDecimal(money));
                }
            } else {
                //获取金蝶用户表id
                String itemId = user.get(0).getItemId();
                //获取主键id
                List<TItem> tItems = tItemService.getItemId(itemId);
                if (tItems.size() > 0) {
                    Integer fitemid = tItems.get(0).getFitemid();
                    //获取t_ItemDetailV 表主键id
                    Integer itemDetaiId = 0;
                    List<TItemdetailv> info = tItmedetailVService.getInfo(fitemid);
                    if (info.size() > 0) {
                        itemDetaiId = info.get(0).getFdetailid();
                    } else {
                        //获取主键id 插入到 t_ItemDetailV 表
                        List<TItemdetailv> infoSort = tItmedetailVService.getInfoSort(1);
                        itemDetaiId = infoSort.get(0).getFdetailid() + 1; // 获取主键id 模拟自增
                        TItemdetailv tItemdetailvKey = new TItemdetailv();
                        tItemdetailvKey.setFitemid(fitemid);
                        tItemdetailvKey.setFitemclassid(1);
                        tItemdetailvKey.setFdetailid(itemDetaiId);
                        tItmedetailVService.insertInfo(tItemdetailvKey);
                    }
                    //分录表插入
                    TVoucherentry tVoucherentry = new TVoucherentry();
                    tVoucherentry.setFvoucherid(Pid); //凭证主表id
                    tVoucherentry.setFentryid(i); //分录号
                    tVoucherentry.setFexplanation(anAbstract); //摘要
                    tVoucherentry.setFaccountid(1031); //科目id 客户
                    tVoucherentry.setFcurrencyid(1); //币别
                    tVoucherentry.setFexchangerate(1d); // 汇率
                    tVoucherentry.setFdc((short) 1); // 余额的方向 0贷方 1借方
                    tVoucherentry.setFamountfor(new BigDecimal(money));// 原币金额
                    tVoucherentry.setFamount(new BigDecimal(money)); //本币金额
                    tVoucherentry.setFquantity(0d); //数量
                    tVoucherentry.setFmeasureunitid(0); //计量单位
                    tVoucherentry.setFunitprice(0d); //单价
                    tVoucherentry.setFinternalind(null); //机制凭证
                    tVoucherentry.setFaccountid2(1031); //对方科目
                    tVoucherentry.setFsettletypeid(0); //结算方式
                    tVoucherentry.setFsettleno(null);
                    tVoucherentry.setFcashflowitem(0);
                    tVoucherentry.setFtaskid(0); // 项目任务id
                    tVoucherentry.setFresourceid(0); // 项目资源id
                    tVoucherentry.setFtransno(null); // 业务号
                    tVoucherentry.setFdetailid(itemDetaiId);  // 项目核算使用id
                    tVoucherEntryService.insertInfo(tVoucherentry);
                    i++;
                    initMoney = initMoney.add(new BigDecimal(money));
                }
            }
        }
        //插入凭证借贷方
        //分录表插入
        TVoucherentry tVoucherentry = new TVoucherentry();
        tVoucherentry.setFvoucherid(Pid); //凭证主表id
        tVoucherentry.setFentryid(i); //分录号
        tVoucherentry.setFexplanation("系统生成贷方凭证"); //摘要
        tVoucherentry.setFaccountid(1032); //科目id 客户
        tVoucherentry.setFcurrencyid(1); //币别
        tVoucherentry.setFexchangerate(1d); // 汇率
        tVoucherentry.setFdc((short) 0); // 余额的方向 0贷方 1借方
        tVoucherentry.setFamountfor(initMoney);// 原币金额
        tVoucherentry.setFamount(initMoney); //本币金额
        tVoucherentry.setFquantity(0d); //数量
        tVoucherentry.setFmeasureunitid(0); //计量单位
        tVoucherentry.setFunitprice(0d); //单价
        tVoucherentry.setFinternalind(null); //机制凭证
        tVoucherentry.setFaccountid2(1032); //对方科目
        tVoucherentry.setFsettletypeid(0); //结算方式
        tVoucherentry.setFsettleno(null);
        tVoucherentry.setFcashflowitem(0);
        tVoucherentry.setFtaskid(0); // 项目任务id
        tVoucherentry.setFresourceid(0); // 项目资源id
        tVoucherentry.setFtransno(null); // 业务号
        tVoucherentry.setFdetailid(25);  // 项目核算使用id
        tVoucherEntryService.insertInfo(tVoucherentry);
        //更新凭证主表贷款和借款总余额
        TVoucher t = new TVoucher();
        t.setFvoucherid(Pid);
        t.setFcredittotal(initMoney);
        t.setFdebittotal(initMoney);
        tVoucherService.updateVoucher(t);
        result.setDataMap("销售凭证插入成功");
        return result;
    }

    //销售凭证导入
    @ApiOperation(value = "",notes = "采购凭证生成")
    @PostMapping("/purchaseVoucher")
    public Result<String> purchaseVoucher(@RequestBody List<Map<String, String>> parameters) {
        if (parameters.size()<1){
            return Result.newError("数组不能为空");
        }
        Result<String> result = Result.newSuccess();
        //查询凭证主表
        Integer voucherNumMax = tVoucherService.getVoucherNumMax();
        Integer fSerialNumMax = tVoucherService.getFSerialNumMax(); //获取凭证表序号最大值
        // 插入凭证主表
        TVoucher tVoucher = new TVoucher();
        tVoucher.setFdate(new Date());
        tVoucher.setFtransdate(new Date());
        tVoucher.setFyear(Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()))); //会计年度
        tVoucher.setFperiod(Integer.valueOf(new SimpleDateFormat("MM").format(new Date()))); //会计期间
        tVoucher.setFgroupid(1); //凭证字内码
        tVoucher.setFnumber(voucherNumMax + 1); //凭证号
        tVoucher.setFreference(null); //参考信息
        tVoucher.setFexplanation("系统生成"); //备注
        tVoucher.setFattachments(0); //附件张数
        tVoucher.setFentrycount(parameters.size()); //分录数 动态获取
        tVoucher.setFdebittotal(new BigDecimal(0)); //借方金额合计初始化
        tVoucher.setFcredittotal(new BigDecimal(0)); //贷方金额合计初始化
        tVoucher.setFinternalind(null); // 机制凭证
        tVoucher.setFchecked(false); //是否审核
        tVoucher.setFposted(false); //是否过账
        tVoucher.setFpreparerid(16394); // 制单人
        tVoucher.setFcheckerid(-1); //审核人
        tVoucher.setFposterid(-1); //记账人
        tVoucher.setFcashierid(-1); // 出纳人
        tVoucher.setFhandler(null); //会计主管
        tVoucher.setFobjectname(null); //对象接口
        tVoucher.setFparameter(null); //接口参数
        tVoucher.setFserialnum(fSerialNumMax+1); //凭证表序号
        tVoucher.setFtrantype(0);
        tVoucher.setFownergroupid(1);
        Integer Pid = tVoucherService.add(tVoucher); // 获取凭证表id

        //获取分录表参数
        int i = 0;
        BigDecimal initMoney = new BigDecimal(0);
        for (Map<String, String> parameter : parameters) {
            String anAbstract = parameter.get("abstract");//获取摘要
            if (anAbstract==null || anAbstract.length() <1){
                return Result.newError(ResultCode.AN_ABSTRACT_NULL);

            }
            String name =  parameter.get("name");//客户名称
            if (name==null || name.length() <1){
                return Result.newError(ResultCode.NAME_NULL);

            }
            String userId =  parameter.get("userId");// 客户id
            if (userId==null || userId.length() <1){
                return Result.newError(ResultCode.USER_ID_NULL);
            }
            String money = parameter.get("money");
            if (money==null || money.length() <1){
                return Result.newError(ResultCode.COMMON_MESSAGE);
            }
            //根据客户id查询金蝶对应客户
            List<VUserInfo> user = vUserInfoService.getUser(userId);
            if (user.size() < 1) {
                //添加客户
                VUserInfo vUserInfo = new VUserInfo();
                String generateString = RandomUtils.generateString(8); //客户自定义id
                vUserInfo.setItemId(generateString);
                vUserInfo.setUserId(userId);
                vUserInfoService.insertUser(vUserInfo);
                TItem tItem = new TItem();
                tItem.setFitemclassid(1);
                tItem.setFparentid(0);
                tItem.setFlevel((short) 1);
                tItem.setFshortnumber(generateString);
                tItem.setFfullnumber(generateString);
                tItem.setFdetail(true);
                tItem.setFdeleted((short) 0);
                tItem.setUuid(UUID.randomUUID().toString());
                tItem.setFname(name);
                tItem.setFnumber(generateString);
                tItemService.insertUser(tItem); //插入到金蝶客户表
                //获取客户表主键id
                List<TItem> tItems = tItemService.getItemId(generateString);
                if (tItems.size() > 0) {
                    Integer fitemid = tItems.get(0).getFitemid();
                    //获取t_ItemDetailV 表主键id
                    Integer itemDetaiId = 0;
                    List<TItemdetailv> info = tItmedetailVService.getInfo(fitemid);
                    if (info.size() > 0) {
                        itemDetaiId = info.get(0).getFdetailid();
                    } else {
                        //获取主键id 插入到 t_ItemDetailV 表
                        List<TItemdetailv> infoSort = tItmedetailVService.getInfoSort(1);
                        itemDetaiId = infoSort.get(0).getFdetailid() + 1; // 获取主键id 模拟自增
                        TItemdetailv tItemdetailvKey = new TItemdetailv();
                        tItemdetailvKey.setFitemid(fitemid);
                        tItemdetailvKey.setFitemclassid(1);
                        tItemdetailvKey.setFdetailid(itemDetaiId);
                        tItmedetailVService.insertInfo(tItemdetailvKey);
                    }
                    //分录表插入
                    TVoucherentry tVoucherentry = new TVoucherentry();
                    tVoucherentry.setFvoucherid(Pid); //凭证主表id
                    tVoucherentry.setFentryid(i); //分录号
                    tVoucherentry.setFexplanation(anAbstract); //摘要
                    tVoucherentry.setFaccountid(1031); //科目id 客户
                    tVoucherentry.setFcurrencyid(1); //币别
                    tVoucherentry.setFexchangerate(1d); // 汇率
                    tVoucherentry.setFdc((short) 1); // 余额的方向 0贷方 1借方
                    tVoucherentry.setFamountfor(new BigDecimal(money));// 原币金额
                    tVoucherentry.setFamount(new BigDecimal(money)); //本币金额
                    tVoucherentry.setFquantity(0d); //数量
                    tVoucherentry.setFmeasureunitid(0); //计量单位
                    tVoucherentry.setFunitprice(0d); //单价
                    tVoucherentry.setFinternalind(null); //机制凭证
                    tVoucherentry.setFaccountid2(1031); //对方科目
                    tVoucherentry.setFsettletypeid(0); //结算方式
                    tVoucherentry.setFsettleno(null);
                    tVoucherentry.setFcashflowitem(0);
                    tVoucherentry.setFtaskid(0); // 项目任务id
                    tVoucherentry.setFresourceid(0); // 项目资源id
                    tVoucherentry.setFtransno(null); // 业务号
                    tVoucherentry.setFdetailid(itemDetaiId);  // 项目核算使用id
                    tVoucherEntryService.insertInfo(tVoucherentry);
                    i++;
                    initMoney = initMoney.add(new BigDecimal(money));
                }
            } else {
                //获取金蝶用户表id
                String itemId = user.get(0).getItemId();
                //获取主键id
                List<TItem> tItems = tItemService.getItemId(itemId);
                if (tItems.size() > 0) {
                    Integer fitemid = tItems.get(0).getFitemid();
                    //获取t_ItemDetailV 表主键id
                    Integer itemDetaiId = 0;
                    List<TItemdetailv> info = tItmedetailVService.getInfo(fitemid);
                    if (info.size() > 0) {
                        itemDetaiId = info.get(0).getFdetailid();
                    } else {
                        //获取主键id 插入到 t_ItemDetailV 表
                        List<TItemdetailv> infoSort = tItmedetailVService.getInfoSort(1);
                        itemDetaiId = infoSort.get(0).getFdetailid() + 1; // 获取主键id 模拟自增
                        TItemdetailv tItemdetailvKey = new TItemdetailv();
                        tItemdetailvKey.setFitemid(fitemid);
                        tItemdetailvKey.setFitemclassid(1);
                        tItemdetailvKey.setFdetailid(itemDetaiId);
                        tItmedetailVService.insertInfo(tItemdetailvKey);
                    }
                    //分录表插入
                    TVoucherentry tVoucherentry = new TVoucherentry();
                    tVoucherentry.setFvoucherid(Pid); //凭证主表id
                    tVoucherentry.setFentryid(i); //分录号
                    tVoucherentry.setFexplanation(anAbstract); //摘要
                    tVoucherentry.setFaccountid(1031); //科目id 客户
                    tVoucherentry.setFcurrencyid(1); //币别
                    tVoucherentry.setFexchangerate(1d); // 汇率
                    tVoucherentry.setFdc((short) 1); // 余额的方向 0贷方 1借方
                    tVoucherentry.setFamountfor(new BigDecimal(money));// 原币金额
                    tVoucherentry.setFamount(new BigDecimal(money)); //本币金额
                    tVoucherentry.setFquantity(0d); //数量
                    tVoucherentry.setFmeasureunitid(0); //计量单位
                    tVoucherentry.setFunitprice(0d); //单价
                    tVoucherentry.setFinternalind(null); //机制凭证
                    tVoucherentry.setFaccountid2(1031); //对方科目
                    tVoucherentry.setFsettletypeid(0); //结算方式
                    tVoucherentry.setFsettleno(null);
                    tVoucherentry.setFcashflowitem(0);
                    tVoucherentry.setFtaskid(0); // 项目任务id
                    tVoucherentry.setFresourceid(0); // 项目资源id
                    tVoucherentry.setFtransno(null); // 业务号
                    tVoucherentry.setFdetailid(itemDetaiId);  // 项目核算使用id
                    tVoucherEntryService.insertInfo(tVoucherentry);
                    i++;
                    initMoney = initMoney.add(new BigDecimal(money));
                }
            }
        }
        //插入凭证借贷方
        //分录表插入
        TVoucherentry tVoucherentry = new TVoucherentry();
        tVoucherentry.setFvoucherid(Pid); //凭证主表id
        tVoucherentry.setFentryid(i); //分录号
        tVoucherentry.setFexplanation("系统生成贷方凭证"); //摘要
        tVoucherentry.setFaccountid(1032); //科目id 客户
        tVoucherentry.setFcurrencyid(1); //币别
        tVoucherentry.setFexchangerate(1d); // 汇率
        tVoucherentry.setFdc((short) 0); // 余额的方向 0贷方 1借方
        tVoucherentry.setFamountfor(initMoney);// 原币金额
        tVoucherentry.setFamount(initMoney); //本币金额
        tVoucherentry.setFquantity(0d); //数量
        tVoucherentry.setFmeasureunitid(0); //计量单位
        tVoucherentry.setFunitprice(0d); //单价
        tVoucherentry.setFinternalind(null); //机制凭证
        tVoucherentry.setFaccountid2(1032); //对方科目
        tVoucherentry.setFsettletypeid(0); //结算方式
        tVoucherentry.setFsettleno(null);
        tVoucherentry.setFcashflowitem(0);
        tVoucherentry.setFtaskid(0); // 项目任务id
        tVoucherentry.setFresourceid(0); // 项目资源id
        tVoucherentry.setFtransno(null); // 业务号
        tVoucherentry.setFdetailid(25);  // 项目核算使用id
        tVoucherEntryService.insertInfo(tVoucherentry);
        //更新凭证主表贷款和借款总余额
        TVoucher t = new TVoucher();
        t.setFvoucherid(Pid);
        t.setFcredittotal(initMoney);
        t.setFdebittotal(initMoney);
        tVoucherService.updateVoucher(t);
        result.setDataMap("销售凭证插入成功");
        return result;
    }

}
